import { FC, useContext, useEffect, useRef } from "react";
import styles from "./index.module.less";
import AnomalyFilter from "./components/AnomalyFilter";
import AnomalyList from "./components/AnomalyList";
import useAnomaly from "../../hooks/useAnomaly";
import { AlertStatus, AISummary } from "../QuestionContainer/components";
import { BigScreenContext } from "../../../../context/BigScreenContext";

const AnomalyContainer: FC = () => {
  // 使用全局异常事件钩子获取所有数据和方法
  const anomalyStore = useAnomaly();
  // 获取setActiveTab函数
  const { setActiveTab } = useContext(BigScreenContext);
  // 添加定时器引用
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 处理点击异常条目事件，添加切换到裂解炉的逻辑
  const handleAnomalyClick = (anomaly: any) => {
    // 先切换到裂解炉标签
    setActiveTab("裂解炉");
    // 然后调用原来的处理函数
    anomalyStore.handleAnomalyClick(anomaly);
  };

  // 设置定时器，每分钟获取一次AI摘要
  useEffect(() => {
    // 立即执行一次
    anomalyStore.fetchAISummary?.();
    
    // 设置定时器，每分钟执行一次
    timerRef.current = setInterval(() => {
      anomalyStore.fetchAISummary?.();
    }, 60000);
    
    // 组件卸载时清理定时器
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    };
  }, []);

  return (
    <div className={styles["anomaly-container"]}>
      <div className={styles["anomaly-box"]}>
        <div className={styles["box-content"]}>
          <AISummary 
            summary={anomalyStore.aiSummary || "等待对话触发..."} 
            isLoading={anomalyStore.aiSummaryLoading}
          />
          <AlertStatus 
            alerts={anomalyStore.alarmInfo} 
            hideTitle
          />
          <div className={styles["anomaly-filter-container"]}>
            <AnomalyFilter 
              onFilter={anomalyStore.handleFilter} 
              onSearch={anomalyStore.handleSearch}
              onInputChange={anomalyStore.handleInputChange}
              filterValue={anomalyStore.currentFilterValue}
              groupValue={anomalyStore.currentGroupValue}
              searchValue={anomalyStore.currentSearchValue} 
            />
            {anomalyStore.evaluationItemsLoading ? (
              <div className={styles["loading-container"]}>加载中...</div>
            ) : (
              <AnomalyList
                anomalies={anomalyStore.filteredAnomalies}
                onItemClick={handleAnomalyClick}
                onItemIconClick={anomalyStore.handleAnomalyIconClick}
                selectedAnomaly={anomalyStore.selectedAnomaly}
              />
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default AnomalyContainer;
